<template>
  <!-- 评论输入区 -->
  <div class="comment-input">
    <textarea v-model="newComment" placeholder="轻轻敲醒沉睡的心灵，让我看看你的点评"></textarea>
    <button @click="submitComment">评论</button>
  </div>
  <div class="comment-section">
    <!-- 评论列表 -->
    <div class="comment-list">
      <div class="comment-item" v-for="comment in comments" :key="comment.articleId + '-' + comment.postUserId">
        <div class="comment">
          <div class="comment-header">
            <span class="comment-avatar"><img :src="getUserAvatar(comment.postUserId)" alt="用户头像"
                style="width: 50px;" /></span>
            <span class="comment-author">{{ comment.postUser.nickname }}@{{ comment.postUser.username }}</span>
            <!-- <span class="comment-author" v-if="isMe(comment.postUserId)">我</span> -->
            <span class="comment-time">{{ formatDate(comment.createTime) }}</span>
            <!-- 点赞数常显示，回复和喜欢按钮在鼠标悬停时显示 -->
            <div class="comment-actions-container">
              <span class="comment-like-count">{{ comment.likeCount }}</span>
              <span class="comment-actions-wrap">
                <span class="comment-actions"><button @click="replyArticle(comment)">回复</button></span>
                <span class="comment-like"><button @click="likeComment(comment)">喜欢</button></span>
              </span>
            </div>
          </div>
          <div class="comment-content">{{ comment.content }}</div>
          <!-- 回复输入框 -->
          <div v-if="activeReplyComment === comment" class="reply-input">
            <textarea v-model="replyContent" placeholder="写下你的回复..."></textarea>
            <button @click="submitReply(comment)">提交回复</button>
            <button @click="cancelReply">取消</button>
          </div>
        </div>

        <!-- 回复列表 -->
        <div class="comment-replies" v-if="comment.replies && comment.replies.length > 0">
          <div class="reply-item" v-for="reply in comment.replies" :key="reply.replyId">
            <div class="reply">
              <div class="reply-content-wrap">
                <div class="reply-header">
                  <span class="reply-avatar"><img :src="getUserAvatar(reply.postUserId)" alt="用户头像"
                      style="width: 30px;" /></span>
                  <span class="reply-author">{{ comment.postUser.nickname }}@{{ comment.postUser.username }}</span>
                  <span class="reply-to">回复 {{ comment.postUser.nickname }}@{{ comment.postUser.username }}:</span>
                  <span class="reply-time">{{ formatDate(reply.createTime) }}</span>
                  <!-- 点赞数常显示，回复和喜欢按钮在鼠标悬停时显示 -->
                  <div class="reply-actions-container">
                    <span class="reply-like-count">{{ reply.likeCount }}</span>
                    <span class="reply-actions-wrap">
                      <span class="reply-actions"><button @click="replyButton(reply)">回复</button></span>
                      <span class="reply-like"><button @click="likeReply(reply)">喜欢</button></span>
                    </span>
                  </div>
                </div>
                <div class="reply-text">{{ reply.content }}</div>
                <!-- 对回复的回复输入框 -->
                <div v-if="activeReplyOnReply === reply" class="reply-input">
                  <textarea v-model="replyToReplyContent" placeholder="写下你的回复..."></textarea>
                  <button @click="submitReplyToReply(reply)">提交回复</button>
                  <button @click="cancelReplyToReply">取消</button>
                </div>
              </div>
            </div>

          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { addComment, getCommentsByArticleId } from '../api/commentApi'
import { useRoute, useRouter } from 'vue-router'
import { UserInforStore } from "@/stores/userInforStore";
import { getUserInfoByUserId } from '../api/userApi'

const route = useRoute()
const articleId = ref(route.params.id)

const getUserAvatar = (userId) => {
  return '/public/log.png';
  if (userId === userStore.userInfor.value?.id) return userStore.userInfor.value.avatar || 'default-avatar.png';
  return 'default-avatar.png';
};

const comments = ref([])

// function buildCommentTree(flatComments) {
//   const commentMap = {};
//   const commentTree = [];

//   flatComments.forEach(comment => {
//     comment.replies = [];
//     commentMap[comment.id] = comment;
//   });

//   flatComments.forEach(comment => {
//     if (comment.replyId === "0") {
//       commentTree.push(commentMap[comment.id]);
//     } else {
//       const parentComment = commentMap[comment.replyId];
//       if (parentComment) {
//         parentComment.replies.push(commentMap[comment.id]);
//       }
//     }
//   });

//   console.log(commentTree);

//   return commentTree;
// }
function buildCommentTree(flatComments) {
  const commentMap = {};
  const commentTree = [];

  // 第一步：初始化所有评论，并放入 map 中
  flatComments.forEach(comment => {
    comment.replies = []; // 初始化 replies 数组
    commentMap[comment.id] = comment;
  });

  // 第二步：按 replyId 构建树形结构
  flatComments.forEach(comment => {
    const parentId = comment.replyId;
    const parent = commentMap[parentId];

    if (!parentId || parentId === '0') {
      // 一级评论
      commentTree.push(commentMap[comment.id]);
    } else if (parent) {
      // 子评论，加入父级的 replies
      parent.replies.push(commentMap[comment.id]);
    }
  });
  console.log(commentTree);

  return commentTree;
}

const getComments = async () => {
  const data = await getCommentsByArticleId(articleId.value)
  console.log(data);
  comments.value = buildCommentTree(data)
}

onMounted(() => {
  getComments()
})

const isMe = async (userId) => {
  const { userInfor } = UserInforStore();
  if (userId === userInfor.id) return true;
  return false;
};

const formatDate = (date) => {
  const now = new Date();
  const diff = now - new Date(date);
  const minutes = Math.floor(diff / 60000);
  if (minutes < 1) return '刚刚';
  if (minutes < 60) return `${minutes}分钟前`;
  const hours = Math.floor(minutes / 60);
  if (hours < 24) return `${hours}小时前`;
  return new Date(date).toLocaleDateString();
};

const newComment = ref('')

const submitComment = async () => {
  if (newComment.value.trim() === '') return;
  const comment = {
    articleId: articleId.value,
    postUserId: 0,
    replyId: 0,
    replyUserId: 0,
    content: newComment.value,
    likeCount: 0,
    createTime: new Date(),
  }
  await addComment(comment).then((res) => {
    console.log(res)
  })
  // comments.value.push(comment)
  await getComments()
  console.log(comments.value);

  newComment.value = ''

}

// const reply = (comment) => {
//   console.log('Reply to comment:', comment)
// }

const likeComment = (comment) => {
  comment.likeCount++;
  console.log('Liked comment:', comment);
};

const likeReply = (reply) => {
  reply.likeCount++;
  console.log('Liked reply:', reply);
};















const activeReplyComment = ref(null) // 当前正在回复的目标评论
const replyContent = ref('')         // 回复内容

const replyArticle = (comment) => {
  activeReplyComment.value = comment
  replyContent.value = ''
}
const submitReply = async (parentComment) => {
  if (!parentComment || replyContent.value.trim() === '') return

  const newReply = {
    articleId: articleId.value,
    postUserId: 0, // 替换为真实用户ID
    replyId: parentComment.id,           // 回复的是这条评论
    replyUserId: parentComment.postUserId, // 回复的目标用户
    content: replyContent.value,
    likeCount: 0,
    createTime: new Date(),
  }

  try {
    await addComment(newReply)
    await getComments() // 刷新评论数据以包含新回复
    replyContent.value = ''
  } catch (error) {
    console.error('提交回复失败:', error)
  }
}
const cancelReply = () => {
  activeReplyComment.value = null
  replyContent.value = ''
}
const activeReplyOnReply = ref(null) // 当前正在对哪个回复进行回复
const replyToReplyContent = ref('')  // 回复内容
const replyButton = (target) => {
  if (target.replyId) {
    // 如果是回复项，则设置 activeReplyOnReply
    activeReplyOnReply.value = target
    replyToReplyContent.value = ''
  } else {
    // 如果是评论项，则设置 activeReplyComment
    activeReplyComment.value = target
    replyContent.value = ''
  }
}
const submitReplyToReply = async (parentReply) => {
  if (!parentReply || replyToReplyContent.value.trim() === '') return

  const newReply = {
    articleId: articleId.value,
    // postUserId: 0, // 替换为真实用户ID
    replyId: parentReply.id,           // 回复的是这条回复
    replyUserId: parentReply.postUserId, // 回复的目标用户
    content: replyToReplyContent.value,
    likeCount: 0,
    createTime: new Date(),
  }

  try {
    await addComment(newReply)
    await getComments() // 刷新评论数据以包含新回复
    replyToReplyContent.value = ''
  } catch (error) {
    console.error('提交回复失败:', error)
  }
}

const cancelReplyToReply = () => {
  activeReplyOnReply.value = null
  replyToReplyContent.value = ''
}
</script>

<style scoped>
.comment-section {
  margin-top: 20px;
}

.comment-list {
  border: 1px solid #ddd;
  padding: 10px;
}

.comment-item {
  margin-bottom: 10px;
}

.comment-header,
.reply-header {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  font-weight: bold;
  position: relative;
}

.comment-avatar,
.reply-avatar {
  margin-right: 10px;
}

.comment-author,
.reply-author,
.comment-time,
.reply-time {
  margin-right: 10px;
}

.comment-actions-container,
.reply-actions-container {
  display: flex;
  align-items: center;
  margin-right: auto;
  /* 靠右对齐 */
}

.comment-like-count,
.reply-like-count {
  margin-right: 5px;
  color: #666;
}

.comment-actions-wrap,
.reply-actions-wrap {
  display: flex;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s ease;
  pointer-events: none;
}

.comment:hover .comment-actions-wrap,
.reply:hover .reply-actions-wrap {
  opacity: 10;
  pointer-events: auto;
}


.comment-actions button,
.comment-like button,
.reply-actions button,
.reply-like button {
  background-color: #f0f0f0;
  border: none;
  padding: 5px 10px;
  cursor: pointer;
  margin-left: 10px;
}

.comment-content,
.reply-text {
  margin-top: 5px;
}

.comment-replies {
  margin-left: 40px;
  margin-top: 10px;
}

.reply-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 10px;
}

.comment-input textarea {
  width: 100%;
  height: 60px;
  padding: 10px;
  box-sizing: border-box;
  margin-top: 10px;
}

.comment-input button {
  margin-bottom: 10px;
  padding: 10px 20px;
  background-color: #ff6b6b;
  color: white;
  border: none;
  cursor: pointer;
}

.comment-input button:hover {
  background-color: #ff5252;
}









.reply-input {
  margin-top: 10px;
  padding: 10px;
  border: 1px solid #eee;
  background-color: #f9f9f9;
}

.reply-input textarea {
  width: 100%;
  height: 60px;
  padding: 10px;
  box-sizing: border-box;
  margin-bottom: 10px;
}

.reply-input button {
  margin-right: 10px;
  padding: 5px 10px;
  background-color: #ff6b6b;
  color: white;
  border: none;
  cursor: pointer;
}

.reply-input button:hover {
  background-color: #ff5252;
}
</style>